﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using yncTech.BusinessObjects;
using System.Data;
using System.Collections;


using EntitySpaces.Interfaces;

public partial class Admin_FinLend_FinLend001b : AdminBasePage
{
    protected decimal? lendId;
    protected string receiptCount = "0";
    protected decimal? thirdUnitId;

    protected void Page_Load(object sender, EventArgs e)
    {
        if (Request.QueryString["lendId"] != null)
        {
            lendId = decimal.Parse(Request.QueryString["lendId"]);
        }

        if (Request.QueryString["thirdUnitId"] != null)
        {
            thirdUnitId = decimal.Parse(Request.QueryString["thirdUnitId"]);
        }

        if (!IsPostBack)
        {
            //txtStartDate.Value = DateTime.Now.AddMonths(-1).Date.ToString(ConstantValue.DateFormat);
            //txtEndate.Value = DateTime.Now.ToString(ConstantValue.DateFormat);
            //txtDocumentStartDate.Value = DateTime.Now.AddMonths(-1).Date.ToString(ConstantValue.DateFormat);
            //txtDocumentEndDate.Value = DateTime.Now.ToString(ConstantValue.DateFormat);
            //txtStoreStartDate.Value = DateTime.Now.AddMonths(-1).Date.ToString(ConstantValue.DateFormat);
            //txtStoreEndDate.Value = DateTime.Now.ToString(ConstantValue.DateFormat);


            //drpCompanyName.SelectedValue = companyName;


            //BFCompanyDicQuery q1 = new BFCompanyDicQuery();
            //q1.Select(q1.CompanyCode).Where(q1.CompanyName == companyName);
            //q1.es.Distinct = true;
            //drpCompany.DataSource = q1.LoadDataTable();
            //drpCompany.DataTextField = "CompanyCode";
            //drpCompany.DataValueField = "CompanyCode";
            //drpCompany.DataBind();



            if (Session["sd"] != null)
            {
                txtStartDate.Value = Session["sd"].ToString();
            }
            if (Session["ed"] != null)
            {
                txtEndate.Value = Session["ed"].ToString();
            }
            if (Session["Dsd"] != null)
            {
                txtDocumentStartDate.Value = Session["Dsd"].ToString();
            }
            if (Session["Ded"] != null)
            {
                txtDocumentEndDate.Value = Session["Ded"].ToString();
            }
            if (Session["Ssd"] != null)
            {
                txtStoreStartDate.Value = Session["Ssd"].ToString();
            }
            if (Session["Sed"] != null)
            {
                txtStoreEndDate.Value = Session["Sed"].ToString();
            }

            if (Session["txtBoxNo"] != null)
            { txtBoxNo.Text = Session["txtBoxNo"].ToString(); }
            if (Session["txtSupplierBoxNo"] != null)
            { txtSupplierBoxNo.Text = Session["txtSupplierBoxNo"].ToString(); }
            if (Session["drpDocType"] != null)
            {
                drpDocType.SelectedValue = Session["drpDocType"].ToString();
            }
            if (Session["drpThirdUnit"] != null)
            {
                drpThirdUnit.SelectedValue = Session["drpThirdUnit"].ToString();
            }

            if (Session["txtKey"] != null)
            { txtKey.Text = Session["txtKey"].ToString(); }
            if (Session["drpCompany"] != null)
            {
                drpCompany.SelectedValue = Session["drpCompany"].ToString();
            }
            if (Session["drpFunctionDept"] != null)
            {
                drpFunctionDept.SelectedValue = Session["drpFunctionDept"].ToString();
            }
            if (Session["txtUserName"] != null)
            { txtUserName.Text = Session["txtUserName"].ToString(); }
            if (Session["txtDocumentsType"] != null)
            { txtDocumentsType.Text = Session["txtDocumentsType"].ToString(); }
            if (Session["txtReferenceTransact"] != null)
            { txtReferenceTransact.Text = Session["txtReferenceTransact"].ToString(); }
            if (Session["txtDocumentSystem"] != null)
            { txtDocumentSystem.Text = Session["txtDocumentSystem"].ToString(); }
            if (Session["txtLogicalSystem"] != null)
            { txtLogicalSystem.Text = Session["txtLogicalSystem"].ToString(); }
        }
    }


    protected void btnSearch_Click(object sender, EventArgs e)
    {
        Session["txtBoxNo"] = txtBoxNo.Text.Trim();
        Session["txtSupplierBoxNo"] = txtSupplierBoxNo.Text.Trim();
        Session["drpDocType"] = drpDocType.SelectedValue;
        Session["txtKey"] = txtKey.Text.Trim();
        Session["drpCompany"] = drpCompany.SelectedValue;
        Session["drpFunctionDept"] = drpFunctionDept.SelectedValue;
        Session["sd"] = txtStartDate.Value;
        Session["ed"] = txtEndate.Value;
        Session["Dsd"] = txtDocumentStartDate.Value;
        Session["Ded"] = txtDocumentEndDate.Value;
        Session["Ssd"] = txtStoreStartDate.Value;
        Session["Sed"] = txtStoreEndDate.Value;
        Session["txtUserName"] = txtUserName.Text.Trim();
        Session["txtDocumentsType"] = txtDocumentsType.Text.Trim();
        Session["txtReferenceTransact"] = txtReferenceTransact.Text.Trim();
        Session["txtDocumentSystem"] = txtDocumentSystem.Text.Trim();
        Session["txtLogicalSystem"] = txtLogicalSystem.Text.Trim();
        Session["drpThirdUnit"] = drpThirdUnit.SelectedValue;
    }

    protected void PageChanged(object sender, DataGridPageChangedEventArgs e)
    {
        //if (string.IsNullOrEmpty(drpCompany.SelectedValue))
        //{
        //    return;
        //}
        
        FinReceiptQuery q1 = new FinReceiptQuery("q1");


        TSCodeTableQuery q2 = new TSCodeTableQuery("q2");
        TSCodeTableQuery q3 = new TSCodeTableQuery("q3");
        TSCodeTableQuery q4 = new TSCodeTableQuery("q4");
        TSCodeTableQuery q6 = new TSCodeTableQuery("q6");
        BFThirdUnitQuery q5 = new BFThirdUnitQuery("q5");
        BFCompanyDicQuery q7 = new BFCompanyDicQuery("q7");
        VReceiptExtInfoQuery q8 = new VReceiptExtInfoQuery("q8");

        TSCodeTableQuery q9 = new TSCodeTableQuery("q9");
        FinBoxQuery q10 = new FinBoxQuery("q10");

        //FinLendReceiptQuery q11 = new FinLendReceiptQuery("q11");



        q1.LeftJoin(q9).On(q1.VoucherDescription == q9.Code);

        q1.LeftJoin(q2).On(q1.FunctionDept == q2.Code);
        q1.LeftJoin(q3).On(q1.StorageStatus == q3.Code);
        q1.LeftJoin(q4).On(q1.VoucherDescription == q4.Code);
        q1.LeftJoin(q5).On(q1.StorageLocation == q5.ThirdUnitID);
        q1.LeftJoin(q6).On(q1.Division == q6.Code);
        q1.LeftJoin(q7).On(q1.CompanyCode == q7.CompanyCode);
        q1.LeftJoin(q8).On(q1.ReceiptID == q8.ReceiptID);

        q1.SelectAll().Select(q1.CreatedDttm, q2.Value1.As("FunctionDeptStr"), q3.Value1.As("StorageStatusStr"), q4.Value1.As("VoucherDescriptionName"), q5.Name.As("StorageLocationStr"), q6.Value1.As("DivisionStr"), q7.CompanyName, q7.CompanyCode, q8.SupplierBoxNo, q8.BoxNo, q9.Value1.As("DocDesc"));

        ArrayList args = new ArrayList();
        ArrayList argsOr = new ArrayList();
        args.Add(q1.StorageLocation==thirdUnitId);
        //args.Add(q1.StorageLocation == drpThirdUnit.SelectedValue);
        args.Add(q1.StorageStatus=="S2");
        args.Add(q1.LendId.IsNull());
        //args.Add(q1.ReceiptID.NotIn(q11.Select(q11.ReceiptID).Where(q11.LendID==lendId)));

        if (!string.IsNullOrEmpty(drpDocType.SelectedValue))
        {
            args.Add(q1.VoucherDescription == drpDocType.SelectedValue);
        }
        if (!string.IsNullOrEmpty(txtKey.Text.Trim()))
        {
            argsOr.Add(q1.DocumentsNo.Like("%" + txtKey.Text.Trim() + "%"));
            argsOr.Add(q1.Reference.Like("%" + txtKey.Text.Trim() + "%"));
            argsOr.Add(q1.ReferenceKey.Like("%" + txtKey.Text.Trim() + "%"));
            argsOr.Add(q1.DocumentHeaderText.Like("%" + txtKey.Text.Trim() + "%"));
            args.Add(q1.Or(argsOr.ToArray()));
        }
        if (!string.IsNullOrEmpty(drpFunctionDept.SelectedValue))
        {
            args.Add(q1.FunctionDept == drpFunctionDept.SelectedValue);
        }
        if (!string.IsNullOrEmpty(txtDocumentStartDate.Value))
        {
            args.Add(q1.VoucherDate >= txtDocumentStartDate.Value);
        }
        if (!string.IsNullOrEmpty(txtDocumentEndDate.Value))
        {
            args.Add(q1.VoucherDate <= DateTime.Parse(txtDocumentEndDate.Value).AddDays(1));
        }
        if (!string.IsNullOrEmpty(txtStoreStartDate.Value))
        {
            args.Add(q1.FirstStorageDate >= txtStoreStartDate.Value);
        }
        if (!string.IsNullOrEmpty(txtStoreEndDate.Value))
        {
            args.Add(q1.FirstStorageDate <= DateTime.Parse(txtStoreEndDate.Value).AddDays(1));
        }
        if (!string.IsNullOrEmpty(txtStartDate.Value))
        {
            args.Add(q1.CreatedDttm >= txtStartDate.Value);
        }
        if (!string.IsNullOrEmpty(txtEndate.Value))
        {
            args.Add(q1.CreatedDttm <= DateTime.Parse(txtEndate.Value).AddDays(1));
        }
        if (!string.IsNullOrEmpty(txtUserName.Text.Trim()))
        {
            args.Add(q1.UserName.Like("%" + txtUserName.Text.Trim() + "%"));
        }
        if (!string.IsNullOrEmpty(txtDocumentsType.Text.Trim()))
        {
            args.Add(q1.DocumentsType.Like("%" + txtDocumentsType.Text.Trim() + "%"));
        }
        if (!string.IsNullOrEmpty(txtReferenceTransact.Text.Trim()))
        {
            args.Add(q1.ReferenceTransact.Like("%" + txtReferenceTransact.Text.Trim() + "%"));
        }
        if (!string.IsNullOrEmpty(txtDocumentSystem.Text.Trim()))
        {
            args.Add(q1.DocumentSystem.Like("%" + txtDocumentSystem.Text.Trim() + "%"));
        }
        if (!string.IsNullOrEmpty(txtLogicalSystem.Text.Trim()))
        {
            args.Add(q1.LogicalSystem.Like("%" + txtLogicalSystem.Text.Trim() + "%"));
        }
        if (!string.IsNullOrEmpty(txtBoxNo.Text.Trim()))
        {
            args.Add(q10.BoxNo.Like("%" + txtBoxNo.Text.Trim() + "%"));
        }
        if (!string.IsNullOrEmpty(txtSupplierBoxNo.Text.Trim()))
        {
            args.Add(q10.SupplierBoxNo.Like("%" + txtSupplierBoxNo.Text.Trim() + "%"));
        }


        q1.Where(args.ToArray()).OrderBy(q1.DocumentsNo.Ascending);

        DataTable tableSorce = q1.LoadDataTable();
        pageGrid.DataSource = tableSorce;
        pageGrid.CurrentPage = e.NewPageIndex;
        pageGrid.DataBind();
    }

    protected override void OnUnload(EventArgs e)
    {
        base.OnUnload(e);
        Session.Remove("drpDocType");
        Session.Remove("txtKey");
        Session.Remove("drpCompany");
        Session.Remove("drpFunctionDept");
        Session.Remove("sd");
        Session.Remove("ed");
        Session.Remove("Dsd");
        Session.Remove("Ded");
        Session.Remove("Ssd");
        Session.Remove("Sed");
        Session.Remove("txtUserName");
        Session.Remove("txtDocumentsType");
        Session.Remove("txtReferenceTransact");
        Session.Remove("txtDocumentSystem");
        Session.Remove("txtLogicalSystem");

        Session.Remove("txtBoxNo");
        Session.Remove("txtSupplierBoxNo");
        Session.Remove("drpThirdUnit");
        
    }

    protected int getYear(object StoreStartDate)
    {
        int result = 0;

        if (StoreStartDate != null && IsDateTime(StoreStartDate.ToString()))
        {
            result = DateTime.Today.Year - 1 - DateTime.Parse(StoreStartDate.ToString()).Year;
            if (result < 0)
            { result = 0; }
        }

        return result;
    }


    private bool IsDateTime(string str)
    {
        DateTime temp;
        return DateTime.TryParse(str, out temp);
    }

    protected void btnAdd_Click(object sender, EventArgs e)
    {
        if (lendId.HasValue && (!string.IsNullOrEmpty(HiddenFieldIds.Value)))
        {
            string[] idList = HiddenFieldIds.Value.Substring(0, HiddenFieldIds.Value.Length - 1).Split(',');

            string storageLocation = string.Empty;
            FinLendReceiptQuery q1 = new FinLendReceiptQuery("q1");
            FinReceiptQuery q2 = new FinReceiptQuery("q2");
            q1.Select(q2.StorageLocation).Where(q1.LendID == lendId.Value);
            q1.InnerJoin(q2).On(q1.ReceiptID == q2.ReceiptID);
            q1.es.Distinct = true;
            DataTable dt = q1.LoadDataTable();
            if (dt.Rows.Count > 0)
            {
                storageLocation = dt.Rows[0]["StorageLocation"].ToString();
            }

            DateTime now = DateTime.Now;
            string currentUser = LoginUserInfo.CurrentUser.LoginName;
            using (esTransactionScope tr = new esTransactionScope())
            {
                q2 = new FinReceiptQuery("q1");
                //q2 = new FinReceiptQuery("q2");
                ArrayList argsOr = new ArrayList();
                for (int i = 0; i < idList.Length; i++)
                {
                    argsOr.Add(q2.ReceiptID == decimal.Parse(idList[i]));                    
                }
                q2.Select(q2.StorageLocation).Where(q1.Or(argsOr.ToArray()));
                //q2.InnerJoin(q2).On(q1.ReceiptID == q2.ReceiptID);
                q2.es.Distinct = true;
                dt = q2.LoadDataTable();
                if (dt.Rows.Count == 1)
                {
                    if (string.IsNullOrEmpty(storageLocation) || (storageLocation == dt.Rows[0]["storageLocation"].ToString()))
                    {
                        for (int j = 0; j < idList.Length; j++)
                        {
                            FinLendReceipt finLendReceipt = new FinLendReceipt();
                            finLendReceipt.ReceiptID = decimal.Parse(idList[j]);
                            finLendReceipt.LendID = lendId;
                            finLendReceipt.CreatedBy = finLendReceipt.UpdatedBy = currentUser;
                            finLendReceipt.CreatedDttm = finLendReceipt.UpdatedDttm = now;
                            finLendReceipt.Save();

                            FinReceipt finReceipt = new FinReceipt();
                            finReceipt.LoadByPrimaryKey(decimal.Parse(idList[j]));
                            finReceipt.LendId = lendId;
                            finReceipt.Save();

                        }
                        FinLend finLend = new FinLend();
                        if (finLend.LoadByPrimaryKey(lendId.Value))
                        {
                            finLend.ThirdUnitID = decimal.Parse(dt.Rows[0]["storageLocation"].ToString());
                            finLend.Save();
                        }

                        ScriptManager.RegisterStartupScript(this, this.GetType(), Guid.NewGuid().ToString(), "showNews('借阅凭证挑选成功！');", true);
                    }
                    else
                    {
                        ScriptManager.RegisterStartupScript(this, this.GetType(), Guid.NewGuid().ToString(), "showNews('选择借阅的凭证必须在同一个存储地！');", true);
                    }
                }
                else
                {
                    if (dt.Rows.Count > 1)
                    {
                        ScriptManager.RegisterStartupScript(this, this.GetType(), Guid.NewGuid().ToString(), "showNews('选择借阅的凭证必须在同一个存储地！');", true);
                    }
                }


                tr.Complete();
            }
        }
    }
    

}